dojo.require("dijit.form.Select");
dojo.require("dijit.Dialog");
dojo.require("dojo.io.iframe");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");

var antennaNameEntries=[];
var possibleStates=[];
var antennaStateDropbox=[];
var stateEntries=[];
var editDialog;
var newDialog;
var uploadDialog;
var stateHandle;
var passwordInput;
var sessionId;
var tabContainerTop;
// this variable carries the info to send to the database routine
// 0: antenna number
// 1: state_id
// 2: name
// 3: description
var setInfoParameters=[];
var connectionProtocol;
var password;
var logInOutHandle;
var isAuthenticated;
var wikiUpdateButton;
var wikiRefreshButton;
var wikiArea;
var imgUploadButtons = [];
var imgUploadHandles = [];
var newStateButton;
var antennaUpdateButtons = [];
var antennaUpdateHandles = [];
var wikiPreviewDiv;
var creoleParser;
var stateAssistanceDiv;
var antennaAssistanceDiv;
var wikiAssistanceDiv;
var stateColumns=["Name","Description","Image","ID"];


function db_getInfo(action,number,options){
  var infoArray = [];
  
  dojo.xhrPost({
      url: "/cgi-bin/obstools/askap_live/dbinterface.pl",
	sync: true,
	content: {action: action, antenna: number,
	  sessionid: sessionId},
	load: function(data,ioargs){
	if (options && options.noSplit == true) {
	  infoArray = data;
	} else {
	  antennaArray=data.split(/\n/);
	  for (var i=0;i<antennaArray.length-1;i++){
	    if (/\|/.test(antennaArray[i])){
	      infoArray[i]=antennaArray[i].split(/\|/);
	    } else {
	      infoArray[i]=antennaArray[i].split(/\s/);
	    }
	  }
	}
      },
	error: function(error,ioargs){
	alert(error);
      }
    });
  
  return infoArray;
}

function db_setInfo(action){
  dojo.xhrPost({
      url: "/cgi-bin/obstools/askap_live/dbinterface.pl",
	sync: true,
	content: {action: action, antenna: setInfoParameters[0],
	  state_id: setInfoParameters[1], name: setInfoParameters[2],
	  description: setInfoParameters[3], authorisation: password,
	  sessionid: sessionId},
	load: function(data,ioargs){
	// reload the page if the database was updated
	//	if (data==""){
	//	  window.location.reload();
	//	}
      },
	error: function(error,ioargs){
	alert(error);
      }
    });
  
}

function imageUpload(eventObj) {
  //  var password=hex_md5(dojo.byId("password").value);
  
  dojo.io.iframe.send({
      url: connectionProtocol+"//www.narrabri.atnf.csiro.au/cgi-bin/"+
	"obstools/askap_live/dbinterface.pl",
	form: "imageForm",
	method: "post",
	content: {action: "upload_image",state_id: setInfoParameters[1],
	  sessionid: sessionId},
	handleAs: "text",
	load: function(data,ioargs){
	//	dojo.byId("password_result").innerHTML=data;
	//	if (data=="good"){
	//	  window.location.reload();
	//	}
	      // close the dialog
	      uploadDialog.hide();
	      // update just the state table
	      fillStateTable(dojo.byId('stateTable'));
      },
	error: function(error,ioargs){
	alert(error);
      }
    });

  
}

function updateWiki(eventObj) {
  setInfoParameters[0]=0;
  setInfoParameters[1]='';
  setInfoParameters[2]='';
  setInfoParameters[3]=wikiArea.value;

  // submit the information
  db_setInfo('update_wiki');

}

function updateAntenna(eventObj) {
  var callingButtonId=this.id;
  var tmp=/^updateAntenna(.*)$/.exec(callingButtonId);
  var antennaNumber=tmp[1];
  
  setInfoParameters[0]=antennaNumber;
  setInfoParameters[1]=antennaStateDropbox[antennaNumber-1].value;
  setInfoParameters[2]=antennaNameEntries[antennaNumber-1].value;
  setInfoParameters[3]="";
  
  // submit the information
  db_setInfo("update_antenna");

  // update just the antenna table
  fillAntennaTable(dojo.byId('antennaTable'));
}

function updateState(eventObj) {
  for (var i=0;i<2;i++){
    if (dojo.byId("newState"+stateColumns[i]).value==""){
      return;
    }
  }
  //    console.log("state id = "+setInfoParameters[1]);
  setInfoParameters[0]=0;
  setInfoParameters[2]=dojo.byId("newStateName").value;
  setInfoParameters[3]=dojo.byId("newStateDescription").value;
  // close the dialog
  newDialog.hide();
  // submit the information
  db_setInfo("update_state");

  // update both the state and antenna tables
  fillStateTable(dojo.byId('stateTable'));
  fillAntennaTable(dojo.byId('antennaTable'));

}

function newState(eventObj) {
  // find the new state inputs
  var newStateInputs=[];
  for (i=0;i<2;i++){
    newStateInputs[i]=dojo.byId("newState"+stateColumns[i]);
    //	console.log("!"+newStateInputs[i].value+"!");
    if (newStateInputs[i].value==""){
      return;
    }
  }
  setInfoParameters[0]=0;
  setInfoParameters[1]=0;
  setInfoParameters[2]=newStateInputs[0].value;
  setInfoParameters[3]=newStateInputs[1].value;
  // close the dialog
  newDialog.hide();
  // submit the information
  db_setInfo("new_state");

  // update both the state and antenna tables
  fillStateTable(dojo.byId('stateTable'));
  fillAntennaTable(dojo.byId('antennaTable'));
}

function showNewStateDialog(eventObj) {
  for (var i=0;i<2;i++){
    dojo.byId("newState"+stateColumns[i]).value="";
  }
  newDialog.set("title","New State");
  
  // make the Submit button do something
  var editButton=dojo.byId("dialogNewButton");
  editButton.innerHTML="Submit";
  dojo.disconnect(stateHandle);
  stateHandle=dojo.connect(editButton,"onclick",editButton,newState);
  
  newDialog.show();
}

function editState(eventObj) {
  // return immediately if we haven't authenticated
  if (isAuthenticated == false){
    return;
  }

  var callingId=this.id;
  var tmp=/^state(.*)\_col(.*)$/.exec(callingId);
  var stateNumber=tmp[1];
  var stateType=tmp[2];
  
  for (var i=0;i<2;i++){
    dojo.byId('newState' + stateColumns[i]).value=
      dojo.byId('state' + stateNumber + '_col' + i).innerHTML;
  }
  newDialog.set("title","Edit State");
  
  // make the Update button do something
  var editButton=dojo.byId("dialogNewButton");
  editButton.innerHTML="Update";
  dojo.disconnect(stateHandle);
  setInfoParameters[1]=dojo.byId("state"+stateNumber+"_col3").innerHTML;
  stateHandle=dojo.connect(editButton,"onclick",editButton,updateState);
  
  newDialog.show();
}

function authenticatedActions() {
  // change what the user can do depending on whether we have
  // successfully authenticated or not
  
  // enable/disable all the update buttons
  wikiUpdateButton.disabled = !isAuthenticated;
  for (var i=0;i<imgUploadButtons.length;i++){
    imgUploadButtons[i].disabled = !isAuthenticated;
  }
  newStateButton.disabled = !isAuthenticated;
  // enable/disable all the entry fields
  wikiArea.disabled = !isAuthenticated;
  for (var i = 0; i < antennaNameEntries.length; i++) {
    antennaNameEntries[i].disabled = !isAuthenticated;
  }
  for (var i = 0; i < antennaUpdateButtons.length; i++) {
    antennaUpdateButtons[i].disabled = !isAuthenticated;
  }
  for (var i = 0; i < antennaStateDropbox.length; i++) {
    antennaStateDropbox[i].disabled = !isAuthenticated;
  }

  // change the assistance text
  if (isAuthenticated == false) {
    var nonAuthText = 'Please authenticate by entering the ASKAP Live! '+
      'administration password in the "Login Password" field at the top '+
      'right of the page, then click the "Login" button. You will be able '+
      'to make changes only after you have authenticated.';
    antennaAssistanceDiv.innerHTML = nonAuthText;
    stateAssistanceDiv.innerHTML = nonAuthText;
    wikiAssistanceDiv.innerHTML = nonAuthText;
  } else {
    antennaAssistanceDiv.innerHTML = 'From this tab you can change the state '+
      'of each antenna in the array.<br /><br />'+
      'Enter the name of the antenna in the text box in the "Name" column '+
      '(this column can be left blank if the antenna does not yet have a '+
      'name), and select the current state of the antenna from the '+
      'dropdown box in the "State" column (or select "undefined" here '+
      'if none of the current states are suitable).<br /><br />'+
      'If you wish to update a particular antenna, make your changes to '+
      'that antenna and then press the "Update" button in that row. Once '+
      'you do this, the information for that antenna will be updated, and '+
      'the whole table will be updated with the information in the database, '+
      'which will have the effect of erasing any changes you made to other '+
      'antenna prior to hitting the "Update" button.<br /><br />'+
      'If you want to make a new state, please switch to the "States" tab.';
    stateAssistanceDiv.innerHTML = 'From this tab you can add and alter the '+
      'possible states of the ASKAP antenna.<br /><br />'+
      'To alter the name or description of an existing state, click on '+
      'either the text in the "Name" or "Description" column. A popup '+
      'dialog will appear with the current text, which you will be able '+
      'to edit. Once you are happy with the name and description, press '+
      'the "Update" button in the popup, after which the database information '+
      'will be changed, and the state table in this tab will be updated.<br />'+
      '<br />To make a new state, click on the "New State" button, which will '+
      'cause a popup dialog to appear with blank text fields for the new '+
      'state name and description. One you are happy with the name and '+
      'description, press the "Submit" button in the popup, after which the '+
      'database information will be changed, and the state table in this '+
      'tab will be updated, along with the "State" dropdown boxes in the '+
      '"Antenna" tab.<br /><br />'+
      'To change the image associated with a particular state, click the '+
      '"Upload Image" button in the appropriate row. A dialog popup will '+
      'then appear, from which you can select an image to upload to the '+
      'server (using the "Browse" button), and upload it (using the '+
      '"Upload" button).';
    wikiAssistanceDiv.innerHTML = 'From this tab you can changed the text '+
      'displayed on the publically accessible ASKAP Live! page.<br /><br />'+
      'Edit the text in the text area, and use the wiki markup '+
      'described in the image to the right where appropriate. You may use '+
      'the "Preview" button below the text area to see what the markup '+
      'will look like; the result will appear in the "Preview" frame at '+
      'the bottom at the tab. Once you are happy with the text, press '+
      'the "Update" button, which will update the information in the '+
      'database, and hence the text on the ASKAP Live! page. The '+
      '"Refresh" button will query the database for the current text, '+
      'which is useful if you think the text may have changed since you '+
      'loaded the admin page.';
  }
}

function refreshWiki(evtObj) {
  fillWiki();
}

function fillWiki() {
  // get the info from the database
  var latestWikiInfo = db_getInfo('wiki_content', 0,
				  { noSplit: true });

  // update the wiki text box
  wikiArea.value = latestWikiInfo;
}

function makeWikiInput() {
  // this function creates a big text box in a tab to edit the text
  // on the ASKAP Live! front page
  var wikiPane = new dijit.layout.ContentPane({
      title: 'Wiki' });
  tabContainerTop.addChild(wikiPane);
  var wikiDiv = wikiPane.containerNode;

  // make the assistance field
  var wikiAssistanceSet = dojo.create('fieldset');
  wikiDiv.appendChild(wikiAssistanceSet);
  wikiAssistanceSet.appendChild(dojo.create('legend', {
	innerHTML: 'Assistance' }));
  wikiAssistanceDiv = dojo.create('div');
  wikiAssistanceSet.appendChild(wikiAssistanceDiv);

  // make a table
  var wikiLayoutTable = dojo.create('table');
  wikiDiv.appendChild(wikiLayoutTable);
  var wikiLayoutRow = dojo.create('tr');
  wikiLayoutTable.appendChild(wikiLayoutRow);
  var wikiLayoutCol = dojo.create('td', {colspan: 3});
  wikiLayoutRow.appendChild(wikiLayoutCol);

  // make the text area
  wikiArea = dojo.create('textarea', {
      id: 'wikiArea', rows: 30, cols: 80 });
  wikiLayoutCol.appendChild(wikiArea);
  // show the wiki format image
  wikiLayoutCol = dojo.create('td');
  wikiLayoutRow.appendChild(wikiLayoutCol);
  var wikiFormatImage = dojo.create('img', {
      src: '/askap_live/creole_cheat_sheet.png' });
  wikiLayoutCol.appendChild(wikiFormatImage);
  // make the update button
  wikiLayoutRow = dojo.create('tr');
  wikiLayoutTable.appendChild(wikiLayoutRow);
  wikiLayoutCol = dojo.create('td');
  wikiLayoutRow.appendChild(wikiLayoutCol);
  wikiUpdateButton = dojo.create('button', {
      type: 'button', innerHTML: 'Update' });
  wikiLayoutCol.appendChild(wikiUpdateButton);
  dojo.connect(wikiUpdateButton, 'onclick', null, updateWiki);
  // make the refresh button
  wikiLayoutCol = dojo.create('td');
  wikiLayoutRow.appendChild(wikiLayoutCol);
  wikiRefreshButton = dojo.create('button', {
      type: 'button', innerHTML: 'Refresh' });
  wikiLayoutCol.appendChild(wikiRefreshButton);
  dojo.connect(wikiRefreshButton, 'onclick', null, refreshWiki);
  // make the preview button
  wikiLayoutCol = dojo.create('td');
  wikiLayoutRow.appendChild(wikiLayoutCol);
  var wikiPreviewButton = dojo.create('button', {
      type: 'button', innerHTML: 'Preview' });
  wikiLayoutCol.appendChild(wikiPreviewButton);
  dojo.connect(wikiPreviewButton, 'onclick', null,
	       generateWikiPreview);

  // make the preview area
  var wikiPreviewSet = dojo.create('fieldset');
  wikiDiv.appendChild(wikiPreviewSet);
  wikiPreviewSet.appendChild(dojo.create('legend', {
	innerHTML: 'Wiki Preview' }));
  wikiPreviewDiv = dojo.create('div');
  wikiPreviewSet.appendChild(wikiPreviewDiv);
  creoleParser = new Parse.Simple.Creole({
      forIE: document.all });
  
}

function generateWikiPreview(evtObj) {
  wikiPreviewDiv.innerHTML = '';
  creoleParser.parse(wikiPreviewDiv, wikiArea.value);
}

function fillStateTable(stateTable) {
  // get the info from the database
  var adminStateInfo=db_getInfo("state_table",0);
  stateEntries=adminStateInfo;
  
  // delete all the current contents
  dojo.empty(stateTable);
  imgUploadButtons = [];
  for (var i = 0; i < imgUploadHandles.length; i++) {
    dojo.disconnect(imgUploadHandles[i]);
  }
  
  // make the table
  var firstRow=dojo.create("thead");
  var columns=stateColumns;
  for (var i=0;i<columns.length;i++){
    var element=dojo.create("td",{innerHTML: columns[i]});
    firstRow.appendChild(element);
  }
  stateTable.appendChild(firstRow);
  
  for (var i=0;i<adminStateInfo.length;i++){
    var rowCol="even";
    if (i%2){
      rowCol="odd";
    }
    var stateRow=dojo.create("tr",{'class': rowCol});
    for (var j=0;j<columns.length;j++){
      var element;
      var elementHTML;
      if (j!=2){
	elementHTML=adminStateInfo[i][j];
      } else {
	// the state image
	// change the protocol if required
	var imageAddress = adminStateInfo[i][j].split(/\:/);
	if (imageAddress[0].match(/^http/)) {
	  if (connectionProtocol == 'https:') {
	    imageAddress[0] = 'https';
	  }
	}
	elementHTML = '<img src="' + imageAddress[0] + ':' + 
	  imageAddress[1] + '" width="50%" ' + 'height="50%" />';
      }
      element=dojo.create("td",{innerHTML: elementHTML,
				id: "state"+i+"_col"+j,
				onmouseover: "this.style.textDecoration='underline'",
				onmouseout: "this.style.textDecoration='none'"});
      if (j<2){
	dojo.connect(element,"onclick",element,editState);
      }    
      stateRow.appendChild(element);
      if (columns[j]=='Name'){
	possibleStates[i+1]=adminStateInfo[i][j];
      }
    }
    // image upload button
    imgUploadButtons[i]=dojo.create("button",{type: "button", innerHTML: "Upload Image",
					      id: "uploadImage"+adminStateInfo[i][3],
					      'class': "uploadImage"});
    imgUploadHandles[i] = dojo.connect(imgUploadButtons[i], 'onclick',
				       imgUploadButtons[i], stateUpload);
    var column=dojo.create("td");
    column.appendChild(imgUploadButtons[i]);
    stateRow.appendChild(column);
    
    stateTable.appendChild(stateRow);
    
  }
}

function makeStateTable() {
  // this function creates the table with the information about the
  // states the antenna can be in
  var statePane = new dijit.layout.ContentPane({
      title: 'States' });
  tabContainerTop.addChild(statePane);
  var stateDiv=statePane.containerNode;

  // make the assistance field
  var stateAssistanceSet = dojo.create('fieldset');
  stateDiv.appendChild(stateAssistanceSet);
  stateAssistanceSet.appendChild(dojo.create('legend', {
	innerHTML: 'Assistance' }));
  stateAssistanceDiv = dojo.create('div');
  stateAssistanceSet.appendChild(stateAssistanceDiv);
  
  // make a table
  var adminStateTable=dojo.create("table",{id: "stateTable"});
  stateDiv.appendChild(adminStateTable);

  // the new state button
  var newStateContainer=dojo.create("div",{'class':"buttonContainer"});
  newStateButton=dojo.create("button",{type:"button",'class':"updateButton",
				       id:"newStateButton",innerHTML:"New State"});
  newStateContainer.appendChild(newStateButton);
  stateDiv.appendChild(newStateContainer);
  dojo.connect(newStateButton,"onclick",newStateButton,showNewStateDialog);
}

function fillAntennaTable(antennaTable) {
  
  // get the info from the database
  var adminAntennaInfo=db_getInfo("antenna_table",0);

  // delete all the current contents
  dojo.empty(antennaTable);
  antennaNameEntries = [];
  antennaUpdateButtons = [];
  antennaStateDropbox = [];
  for (var i = 0; i < antennaUpdateHandles.length; i++) {
    dojo.disconnect(antennaUpdateHandles[i]);
  }
  
  // make the table
  var firstRow=dojo.create("thead");
  var columns=['Number','Name','State','Updated','Latitude','Longitude'];
  for (var i=0;i<columns.length;i++){
    var element=dojo.create("td",{innerHTML: columns[i]});
    firstRow.appendChild(element);
  }
  antennaTable.appendChild(firstRow);
  
  for (var i = 0; i < adminAntennaInfo.length; i++) {
    var rowCol="even";
    if (i%2){
      rowCol="odd";
    }
    var antennaRow=dojo.create('tr', { 'class': rowCol });
    for (var j=0;j<columns.length;j++){
      var element;
      var elementHTML=adminAntennaInfo[i][j];
      // alter the HTML according to what column we're in
      if (columns[j]=='Updated'){
	var tmp=/^(.*)\..*$/i.exec(elementHTML);
	elementHTML=tmp[1];
      } 
      if (columns[j]=='State'){
	antennaStateDropbox[i]=dojo.create("select",{dojoType:"dijit.form.Select"});
	for (var k=0;k<possibleStates.length;k++){
	  var stateOption=dojo.create("option",{value: possibleStates[k],
						innerHTML: possibleStates[k]});
	  if (possibleStates[k]==elementHTML){
	    stateOption.selected="selected";
	  }
	  antennaStateDropbox[i].appendChild(stateOption);
	}
	element=dojo.create("td");
	element.appendChild(antennaStateDropbox[i]);
      } else if (columns[j]=='Name'){
	antennaNameEntries[i]=dojo.create("input",{type: "text", value: elementHTML});
	element=dojo.create("td");
	element.appendChild(antennaNameEntries[i]);
      } else {
	element=dojo.create("td",{innerHTML: elementHTML});
      }
      antennaRow.appendChild(element);
    }
    // add an update button
    antennaUpdateButtons[i] = dojo.create('button', 
					  {type: 'button',
					   innerHTML: 'Update',
					   id: 'updateAntenna'+
					   adminAntennaInfo[i][0],
					   'class': 'antennaUpdate'});
    var column=dojo.create("td");
    column.appendChild(antennaUpdateButtons[i]);
    antennaRow.appendChild(column);
    antennaTable.appendChild(antennaRow);
    // connect this button to an action
    antennaUpdateHandles[i] = dojo.connect(antennaUpdateButtons[i], 'onclick',
					   antennaUpdateButtons[i],
					   updateAntenna);
  }

}

function makeAntennaTable() {
  // this function creates the table with the information about the
  // antennas from the database information
  var antennaPane = new dijit.layout.ContentPane({
      title: 'Antenna' });
  tabContainerTop.addChild(antennaPane);
  var antennaDiv=antennaPane.containerNode;

  // make the assistance field
  var antennaAssistanceSet = dojo.create('fieldset');
  antennaDiv.appendChild(antennaAssistanceSet);
  antennaAssistanceSet.appendChild(dojo.create('legend', {
	innerHTML: 'Assistance' }));
  antennaAssistanceDiv = dojo.create('div');
  antennaAssistanceSet.appendChild(antennaAssistanceDiv);
  
  // make a table
  var adminAntennaTable=dojo.create("table",{id: "antennaTable"});
  antennaDiv.appendChild(adminAntennaTable);

}

function createEditDialog() {
  // attach the edit dialog window
  editDialog=dijit.byId("dialogEdit");
  // put some stuff in there
  var editLabel=dojo.create("div",{id: "editLabel"});
  editDialog.domNode.appendChild(editLabel);
  var editInput = dojo.create('input', {
      type: 'text', 'class': 'editDialog', id: 'dialogInput' });
  editDialog.domNode.appendChild(editInput);
  var editCenter = dojo.create('div', { 'class': 'buttonContainer' });
  var editUpdate = dojo.create('button', {
      type: 'button', 'class': 'updateButton',
      id: 'dialogButton', innerHTML: 'Update' });
  
  editCenter.appendChild(editUpdate);
  editDialog.domNode.appendChild(editCenter);
  // make the Update button do something
  var dialogInput=dojo.byId("dialogInput");
  var editButton=dojo.byId("dialogButton");
  dojo.connect(editButton,"onclick",dialogInput,updateState);
}    

function createNewDialog() {
  // attach the edit dialog window
  newDialog = new dijit.Dialog({
      title: "New State"
    });
  // put some stuff in there
  var editCenter = dojo.create('div', { 'class': 'buttonContainer' });
  var newStateTable=dojo.create("table",{id: "newStateTable"});
  var firstRow=dojo.create("thead");
  var columns=stateColumns;
  for (var i=0;i<2;i++){
    var element=dojo.create("td",{innerHTML: columns[i]});
    firstRow.appendChild(element);
  }
  newStateTable.appendChild(firstRow);
  var stateRow = dojo.create('tr', { 'class': 'even' });
  for (var i=0;i<2;i++){
    var stateColumn=dojo.create("td");
    var element=dojo.create("input",{type:"text",id:"newState"+columns[i]});
    stateColumn.appendChild(element);
    stateRow.appendChild(stateColumn);
  }
  newStateTable.appendChild(stateRow);
  editCenter.appendChild(newStateTable);
  var editUpdate = dojo.create('button', {
      type: 'button', 'class': 'updateButton',
      id: 'dialogNewButton', innerHTML: 'Submit' });
  
  editCenter.appendChild(editUpdate);
  newDialog.domNode.appendChild(editCenter);
  
}    

function createUploadDialog() {
  uploadDialog = new dijit.Dialog({
      title: "Image Upload"
    });
  var uploadForm=dojo.create("form",{method: "post",enctype:"multipart/form-data",
				     id: "imageForm"});
  var uploadTable=dojo.create("table");
  var uploadRow=dojo.create("tr");
  var uploadLabel=dojo.create("th",{innerHTML: "Image:"});
  uploadRow.appendChild(uploadLabel);
  var uploadColumn=dojo.create("td");
  var uploadFileBox=dojo.create("input",{type:"file",name:"image",
					 id:"imageFile"});
  uploadColumn.appendChild(uploadFileBox);
  uploadRow.appendChild(uploadColumn);
  uploadTable.appendChild(uploadRow);
  uploadForm.appendChild(uploadTable);
  //    uploadDialog.domNode.appendChild(uploadTable);
  var uploadDiv = dojo.create('div', { 'class': 'buttonContainer' });
  var uploadButton=dojo.create("button",{type:"button",id:"uploadButton",
					 innerHTML:"Upload"});
  dojo.connect(uploadButton,'onclick',imageUpload);
  uploadDiv.appendChild(uploadButton);
  uploadForm.appendChild(uploadDiv);
  //    uploadDialog.domNode.appendChild(uploadDiv);
  uploadDialog.domNode.appendChild(uploadForm);
}

function stateUpload(eventObj) {
  var callingButtonId=this.id;
  var tmp=/^uploadImage(.*)$/.exec(callingButtonId);
  //    console.log("uploading to state "+tmp[1]);
  setInfoParameters[1]=tmp[1];
  
  uploadDialog.show();
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}

function attemptLogout() {
  // attempt to log out
  db_setInfo('deauthenticate');
  loginBox();
  // update the page functions
  authenticatedActions();
}

function attemptLogin() {
  // attempt to log in
  if (!passwordInput) {
    // oops, called when already logged in or something
    return;
  }
  password = hex_md5(passwordInput.value);
  // console.log('hexed p/w is '+password);
  db_setInfo('authenticate');
  // reset the password in memory, we'll use the session ID
  // to authenticate from now on
  password = "";
  // remake the login box if necessary
  loginBox();
  // update the page functions
  authenticatedActions();
}

function loginBox() {
  // check for an existing session ID cookie
  isAuthenticated = false;
  if (logInOutHandle) {
    dojo.disconnect(logInOutHandle);
  }
  if (readCookie('sessionId')) {
    // try to login in with the current session ID
    sessionId = readCookie('sessionId');
    var authPositive = db_getInfo('check_authorisation',0);
    if (authPositive[0][0] == '1') {
      isAuthenticated = true;
    }
  } else {
    // make a new session ID
    sessionId=Math.random().toString().substring(2);
    //	console.log('new session ID = '+sessionId);
    createCookie('sessionId',sessionId);
  }
  if (isAuthenticated == false) {
    // not authenticated, make the login box
    var loginDiv = dojo.byId('login');
    dojo.empty(loginDiv);
    var loginTable = dojo.create('table',{
	'class': 'passwordTable' });
    var loginRow = dojo.create('tr');
    loginTable.appendChild(loginRow);
    var loginCol = dojo.create('th', { innerHTML: 'Login Password' });
    loginRow.appendChild(loginCol);
    loginRow = dojo.create('tr');
    loginTable.appendChild(loginRow);
    loginCol = dojo.create('td');
    loginRow.appendChild(loginCol);
    passwordInput = dojo.create('input', { type: 'password',
					   id: 'password' });
    loginCol.appendChild(passwordInput);
    loginRow = dojo.create('tr');
    loginTable.appendChild(loginRow);
    loginCol = dojo.create('th');
    loginRow.appendChild(loginCol);
    var loginButton = dojo.create('button', { type: 'button',
					      id: 'loginButton',
					      innerHTML: 'Login' });
    loginCol.appendChild(loginButton);
    loginDiv.appendChild(loginTable);
    // connect the login button to the login routine
    var logInOutHandle = dojo.connect(loginButton, 'onclick',
				      null, attemptLogin);
  } else {
    // we are authenticated, make the logout box
    var loginDiv = dojo.byId('login');
    dojo.empty(loginDiv);
    var loggedInTable = dojo.create('table',{
	'class': 'passwordTable' });
    var loggedInRow = dojo.create('tr');
    loggedInTable.appendChild(loggedInRow);
    var loggedInCol = dojo.create('th', { innerHTML: 'Logged in.' });
    loggedInRow.appendChild(loggedInCol);
    loggedInRow = dojo.create('tr');
    loggedInTable.appendChild(loggedInRow);
    loggedInCol=dojo.create('th');
    loggedInRow.appendChild(loggedInCol);
    var logoutButton=dojo.create('button', { type: 'button',
					     id: 'logoutButton',
					     innerHTML: 'Logout' });
    loggedInCol.appendChild(logoutButton);
    loginDiv.appendChild(loggedInTable);
    // connect the logout button to the logout routine
    var logInOutHandle = dojo.connect(logoutButton, 'onclick',
				      null, attemptLogout);
  }
}

function init(){
  // check for SSL connection
  connectionProtocol = 
    window.parent.document.location.protocol;
  //  console.log(connectionProtocol);
  if (connectionProtocol == 'https:') {
    // show the login box
    loginBox();
  }
  
  // make our tab container
  tabContainerTop = new dijit.layout.TabContainer({
      style: "height: 100%; width: 100%" },
    'tc');
  
  // make our tables
  makeAntennaTable();
  makeStateTable();
  makeWikiInput();
  tabContainerTop.startup();

  // fill the tables with data
  fillStateTable(dojo.byId('stateTable'));
  fillAntennaTable(dojo.byId('antennaTable'));
  fillWiki();
  
  // make our two state dialogs
  createUploadDialog();
  createNewDialog();

  // start by enabling/disabling the proper areas
  authenticatedActions();
}

dojo.addOnLoad(init);
